package com.matt.controller.web.care;

import com.dotflat.util.excelUtil.ExcelDataVo;
import com.dotflat.util.excelUtil.PackExcelSheetsDataUtil;
import com.matt.commons.dto.sso.StaffDTO;
import com.matt.commons.exception.BusinessException;
import com.matt.commons.model.StatusResponse;
import com.matt.commons.page.PagerQuery;
import com.matt.controller.pad.care.CareBaseController;
import com.matt.domain.Children;
import com.matt.domain.Classes;
import com.matt.domain.care.*;
import com.matt.domain.vo.DailyVo;
import com.matt.foundation.ext.aliyun.OSSProcessService;
import com.matt.foundation.model.ErrorCode;
import com.matt.foundation.model.MemVerificationCache;
import com.matt.foundation.utils.DateUtil;
import com.matt.foundation.vo.care.HLChildDailyRecordPageVO;
import com.matt.service.ChildrenService;
import com.matt.service.ClassesService;
import com.matt.service.care.*;
import com.matt.service.care.po.HLDailyRecordPO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

import static com.matt.foundation.constant.RequestConstant.TICKET;

;

@RestController
@RequestMapping("/web/daily")
@Slf4j
@Api(tags = "宝宝一日 - 统计")
public class WebDailyController {

    @Autowired
    ClassesService classesService;

    @Autowired
    ChildrenService childrenService;

    @Autowired
    HLSleepRecordService sleepRecordService;

    @Autowired
    HLFeedingRecordService feedingRecordService;

    @Autowired
    HLPottyRecordService pottyRecordService;

    @Autowired
    HLMedicationRecordService medicationRecordService;

    @Autowired
    HLTemperatureRecordService temperatureRecordService;

    @Autowired
    HLHandoverRecordService hlHandoverRecordService;

    @Autowired
    private OSSProcessService ossProcessService;

    @Autowired
    HLMoreRecordService moreRecordService;

    @Value("${aliyun.oss.fileServerPrefix}")
    private String IMG_SERVICE_PREFIX;

    @Autowired
    protected MemVerificationCache cache;

    @ApiOperation(value = "")
    @GetMapping("/classCount")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "classId", value = "班级ID", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "startTime", value = "开始时间", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "endTime", value = "结束时间", required = true, dataType = "String"),
    })
    public StatusResponse classCount(@RequestHeader(TICKET) String ticket, HttpServletResponse response, String classId, String startTime, String endTime) {
        StaffDTO staff = cache.getStaff(ticket);
        Date startTimeDate = DateUtil.parseToDateMilisV3(startTime);
        Date endTimeDate = DateUtil.parseToDateMilisV2(endTime);
        PagerQuery pagerQuery = new PagerQuery();
        pagerQuery.setPageNum(0);
        pagerQuery.setPageSize(999);
        //班级信息
        Classes classes = classesService.getClassesById(staff.getAreaId(), classId);
        //学生集合
        Page<Children> page = classesService.getChildIdsByClassesId(staff.getAreaId(), classId, pagerQuery);
        //获取班级学生
        List<String> childIds = page.getContent().stream().map(k -> k.getId()).collect(Collectors.toList());
        if (childIds.size() == 0) {
            throw new BusinessException(ErrorCode.UNDEFINED, "班级未添加学生！");
        }
        //护理记录 - 体温
        List<HLTemperatureRecord> temperatureRecordList = temperatureRecordService.childrenIdListDailyRecords(staff.getAreaId(), childIds, startTimeDate, endTimeDate, null);
        //护理记录 - 喂食
        List<HLFeedingRecord> feedingRecordList = feedingRecordService.childrenIdListDailyRecords(staff.getAreaId(), childIds, startTimeDate, endTimeDate, null);
        //护理记录 - 睡觉
        List<HLSleepRecord> sleepRecordList = sleepRecordService.childrenIdListDailyRecords(staff.getAreaId(), childIds, startTimeDate, endTimeDate, null);
        //护理记录 - 大小便
        List<HLPottyRecord> pottyRecordList = pottyRecordService.childrenIdListDailyRecords(staff.getAreaId(), childIds, startTimeDate, endTimeDate, null);
        //护理记录 - 服药
        List<HLMedicationRecord> medicationRecordList = medicationRecordService.childrenIdListDailyRecords(staff.getAreaId(), childIds, startTimeDate, endTimeDate, null);
        //护理记录 - 更多
        List<HLMoreRecord> moreRecordList = moreRecordService.childrenIdListDailyRecords(staff.getAreaId(), childIds, startTimeDate, endTimeDate, null);
        //护理记录 - 药品交接
//        List<HLHandoverRecord> handoverRecordList =  hlHandoverRecordService.childrenIdListDailyRecords(staff.getAreaId(),childIds,startTimeDate, endTimeDate,null);
        //所有日期
        List<Date> dateList = DateUtil.getBetweenDates(startTimeDate, endTimeDate);
        if (dateList.size() > 32) {
            throw new BusinessException(ErrorCode.UNDEFINED, "日期跨度过大！");
        }
        if (temperatureRecordList.size() == 0 && feedingRecordList.size() == 0 && sleepRecordList.size() == 0
                && pottyRecordList.size() == 0 && medicationRecordList.size() == 0) {
            throw new BusinessException(ErrorCode.UNDEFINED, "班级所选日期没有宝宝一日记录！");
        }
        Map<String, List<DailyVo>> listMap = new HashMap<>();
        //循环宝宝
        for (int i = 0; i < page.getContent().size(); i++) {
            //宝宝一日
            List<DailyVo> dailyVoList = new ArrayList<>();
            String childId = page.getContent().get(i).getId();
            String childName = page.getContent().get(i).getName();
            for (int j = 0; j < dateList.size(); j++) {
                DailyVo dailyVo = new DailyVo();
                dailyVo.setName(childName);
                dailyVo.setBeginDate(DateUtil.datePath(dateList.get(j)));
                dailyVo.setClassName(classes.getName());
                //体温记录
                String temperatureRecord = getTemperatureRecordString(childId, dateList.get(j), temperatureRecordList);
                dailyVo.setTemperature(temperatureRecord);
                //睡眠记录
                String sleepRecord = getSleepRecordString(childId, dateList.get(j), sleepRecordList);
                dailyVo.setSleep(sleepRecord);
                //饮食记录
                String feedingRecord = getFeedingRecordString(childId, dateList.get(j), feedingRecordList);
                dailyVo.setFeeding(feedingRecord);
                //换尿布次数 和 大小便次数
                String pottyRecord = getPottyRecordString(childId, dateList.get(j), pottyRecordList, dailyVo);
                dailyVo.setPotty(pottyRecord);
                //喂药记录
                String medicationRecord = getMedicationRecordString(childId, dateList.get(j), medicationRecordList);
                dailyVo.setMedication(medicationRecord);

                //更多记录有换尿布
                String more = getMoreRecordString(childId, dateList.get(j), moreRecordList,dailyVo);
                dailyVo.setMore(more);

                //更多记录喂奶
                String moreNursery = getMoreRecordString1(childId, dateList.get(j), moreRecordList,dailyVo);
                dailyVo.setMoreNursery(moreNursery);

                if (StringUtils.equals(temperatureRecord,"") && StringUtils.equals(sleepRecord,"") &&
                        StringUtils.equals(feedingRecord,"") && StringUtils.equals(pottyRecord,"") &&
                        StringUtils.equals(medicationRecord,"") &&  StringUtils.equals(more,"")
                        &&  StringUtils.equals(moreNursery,"")){
                    continue;
                }
                dailyVoList.add(dailyVo);
            }
            listMap.put(childId, dailyVoList);
        }

        //列名称
        List<String> titleList = new ArrayList<>();
        titleList.add("宝宝姓名");
        titleList.add("班级");
        titleList.add("日期");
        titleList.add("体温状况");
        titleList.add("睡眠情形");
        titleList.add("饮食方面");
        titleList.add("换尿布状况");
        titleList.add("如厕状况");
        titleList.add("用药需求");
        titleList.add("更多换尿布状况");
        titleList.add("更多喂奶状况");

        //属性名称
        List<String> attributeList = new ArrayList<>();
        attributeList.add("name");
        attributeList.add("className");
        attributeList.add("beginDate");
        attributeList.add("temperature");
        attributeList.add("sleep");
        attributeList.add("feeding");
        attributeList.add("pottyDiaper");
        attributeList.add("potty");
        attributeList.add("medication");
        attributeList.add("more");
        attributeList.add("moreNursery");
        // 封装需要导出的数据
        List<ExcelDataVo> excelDataVoList = new ArrayList<>();

        for (int j = 0; j < page.getContent().size(); j++) {
            String childName = "";
            String childId = page.getContent().get(j).getId();
            childName = page.getContent().get(j).getName();
            List<DailyVo> dailyVoList = listMap.get(childId);
            // 封装学生信息
            ExcelDataVo excelDataSheetOne = new ExcelDataVo();
            excelDataSheetOne.setSheetName(childName);
            excelDataSheetOne.setSheetTopColHeaderTitle(childName + "宝宝一日信息统计");
            excelDataSheetOne.setSheetTopColHeaderName(titleList.toArray(new String[titleList.size()]));
            excelDataSheetOne.setSheetTopColHeaderAttribute(attributeList.toArray(new String[attributeList.size()]));
            List<Map<String, Object>> mapList = dailyVoList.stream().map(it -> {
                Map<String, Object> apiMap = new HashMap<>();
                apiMap.put("name", it.getName());
                apiMap.put("className", it.getClassName());
                apiMap.put("beginDate", it.getBeginDate());
                apiMap.put("temperature", it.getTemperature());
                apiMap.put("sleep", it.getSleep());
                apiMap.put("feeding", it.getFeeding());
                apiMap.put("pottyDiaper", it.getPottyDiaper());
                apiMap.put("potty", it.getPotty());
                apiMap.put("medication", it.getMedication());
                apiMap.put("more", it.getMore());
                apiMap.put("moreNursery", it.getMoreNursery());
                return apiMap;
            }).collect(Collectors.toList());
            excelDataSheetOne.setSheetDataList(mapList);
            excelDataVoList.add(excelDataSheetOne);
        }

        String url = "";
        // 导出数据
        try {
            url = new PackExcelSheetsDataUtil().packExcelSheetsData(response, "学生基础信息", excelDataVoList);
        } catch (Exception e) {
            throw new Exception("导出异常!");
        } finally {
            File outputFile = new File(url);
            String uploadPath = "teach/file/children_export_excel/" + DateTime.now().toString("yyyy-MM") + "/" +classes.getName()+startTime+"~" +endTime +"宝宝一日信息报表.xlsx";
            String relativePath = ossProcessService.aliyunOssUpload(uploadPath, outputFile);
            String uploadedResult = IMG_SERVICE_PREFIX + relativePath;
            return StatusResponse.success(uploadedResult);
        }
    }



    //体温记录
    public String getTemperatureRecordString(String childId, Date time, List<HLTemperatureRecord> temperatureRecordList) {
        String time_v1 = DateUtil.formatDayToStr(time);
        String[] temperatureRecord = temperatureRecordList.stream().filter(s -> StringUtils.equals(s.getChildId(), childId))
                .filter(s -> DateUtil.formatDayToStr(s.getEventTime()).equals(time_v1)).map(o -> {
                    Integer temperature = o.getTemperature();
                    return DateUtil.formatDateToHmStr(o.getEventTime()) + "\n" + temperature.toString().substring(0, 2) + "." + temperature.toString().substring(2, 3) + "°C" + "\n\n";
                }).toArray(String[]::new);
        String temperatureRecordString = "";
        for (int i = 0; i < temperatureRecord.length; i++) {
            if (!temperatureRecord[i].equals("")) {
                temperatureRecordString += temperatureRecord[i];
            }
        }
        return temperatureRecordString;
    }

    //睡眠记录
    public String getSleepRecordString(String childId, Date time, List<HLSleepRecord> sleepRecordList) {
        String time_v1 = DateUtil.formatDayToStr(time);
        String[] sleepRecord = sleepRecordList.stream().filter(s -> StringUtils.equals(s.getChildId(), childId))
                .filter(s -> DateUtil.formatDayToStr(s.getEventTime()).equals(time_v1)).map(o -> {
                    return DateUtil.formatDateToHmStr(o.getSleepTime()) + "~" + DateUtil.formatDateToHmStr(o.getWakeupTime()) + "\n\n";
                }).toArray(String[]::new);
        String sleepRecordString = "";
        for (int i = 0; i < sleepRecord.length; i++) {
            if (!sleepRecord[i].equals("")) {
                sleepRecordString += sleepRecord[i];
            }
        }
        return sleepRecordString;
    }

    //饮食记录
    public String getFeedingRecordString(String childId, Date time, List<HLFeedingRecord> feedingRecordList) {
        String time_v1 = DateUtil.formatDayToStr(time);
        String[] sleepRecord = feedingRecordList.stream().filter(s -> StringUtils.equals(s.getChildId(), childId))
                .filter(s -> DateUtil.formatDayToStr(s.getEventTime()).equals(time_v1)).map(o -> {
                    return DateUtil.formatDateToHmStr(o.getEventTime()) + "\n"
                            + getFeedingType(o.getDiet()) + "：" + o.getFood() + " | 喝水：" + (o.getLiquidQuantity() == null ? "0" : o.getLiquidQuantity()) +
                            "mL | 食量：" + getQuantity(o.getQuantity()) + "\n\n";
                }).toArray(String[]::new);
        String sleepRecordString = "";
        for (int i = 0; i < sleepRecord.length; i++) {
            if (!sleepRecord[i].equals("")) {
                sleepRecordString += sleepRecord[i];
            }
        }
        return sleepRecordString;
    }

    String getFeedingType(Integer diet) {
        switch (diet) {
            case 0:
                return "随餐";
            case 1:
                return "早餐";
            case 2:
                return "上午点心";
            case 3:
                return "中餐";
            case 4:
                return "下午点心";
            case 5:
                return "晚餐";
        }
        return "随餐";
    }

    String getQuantity(Integer quantity) {
        switch (quantity) {
            case 0:
                return "正常";
            case 1:
                return "剩饭";
            case 2:
                return "加量";
        }
        return "正常";
    }

    //大小便记录
    public String getPottyRecordString(String childId, Date time, List<HLPottyRecord> pottyRecordList, DailyVo dailyVo) {
        String time_v1 = DateUtil.formatDayToStr(time);
        String[] pottyRecord = pottyRecordList.stream().filter(s -> StringUtils.equals(s.getChildId(), childId)).filter(s -> DateUtil.formatDayToStr(s.getEventTime()).equals(time_v1)).map(o -> {
            return DateUtil.formatDateToHmStr(o.getEventTime()) + "\n如厕：" +
                    o.getTypeStr() + "\n\n";
        }).toArray(String[]::new);
        //换尿布次数
        int count = (int) pottyRecordList.stream().filter(s -> StringUtils.equals(s.getChildId(), childId))
                .filter(s -> DateUtil.formatDayToStr(s.getEventTime()).equals(time_v1)).filter(s -> s.getDiaper()).count();
        if (count>0){
            dailyVo.setPottyDiaper("在托婴中心托育时段共更换尿布" + count + "次");
        }
        String pottyRecordString = "";
        for (int i = 0; i < pottyRecord.length; i++) {
            if (!pottyRecord[i].equals("")) {
                pottyRecordString += pottyRecord[i];
            }
        }
        return pottyRecordString;
    }

    //更多记录
    public String getMoreRecordString(String childId, Date time, List<HLMoreRecord> moreRecordList, DailyVo dailyVo) {
        String time_v1 = DateUtil.formatDayToStr(time);
        String[] pottyRecord = moreRecordList.stream().filter(s -> StringUtils.equals(s.getChildId(), childId)).filter(s -> DateUtil.formatDayToStr(s.getEventTime()).equals(time_v1)).map(o -> {
            return DateUtil.formatDateToHmStr(o.getEventTime()) + "\n换尿布：" +
                    o.getMoreType().equals(1) + "\n\n";
        }).toArray(String[]::new);
        //换尿布次数
        int count = (int) moreRecordList.stream().filter(s -> StringUtils.equals(s.getChildId(), childId))
                .filter(s -> DateUtil.formatDayToStr(s.getEventTime()).equals(time_v1)).filter(s -> s.getDiaper()).count();
        if (count>0){
            dailyVo.setPottyDiaper("在托婴中心托育时段共更换尿布" + count + "次");
        }
        String pottyRecordString = "";
        for (int i = 0; i < pottyRecord.length; i++) {
            if (!pottyRecord[i].equals("")) {
                pottyRecordString += pottyRecord[i];
            }
        }
        return pottyRecordString;
    }

    private String getMoreRecordString1(String childId, Date time, List<HLMoreRecord> moreRecordList, DailyVo dailyVo) {
        String time_v1 = DateUtil.formatDayToStr(time);
        String[] pottyRecord = moreRecordList.stream().filter(s -> StringUtils.equals(s.getChildId(), childId)).filter(s -> DateUtil.formatDayToStr(s.getEventTime()).equals(time_v1)).map(o -> {
            return DateUtil.formatDateToHmStr(o.getEventTime()) + "\n喂奶：" +
                    o.getMoreType().equals(0) + "\n\n";
        }).toArray(String[]::new);
        //换尿布次数
        int count = (int) moreRecordList.stream().filter(s -> StringUtils.equals(s.getChildId(), childId))
                .filter(s -> DateUtil.formatDayToStr(s.getEventTime()).equals(time_v1)).filter(s -> s.getNursery()).count();
        if (count>0){
            dailyVo.setPottyDiaper("在托婴中心托育时段共喂奶" + count + "次");
        }
        String pottyRecordString = "";
        for (int i = 0; i < pottyRecord.length; i++) {
            if (!pottyRecord[i].equals("")) {
                pottyRecordString += pottyRecord[i];
            }
        }
        return pottyRecordString;
    }
    public String getMedicationRecordString(String childId, Date time, List<HLMedicationRecord> medicationRecordList) {
        String time_v1 = DateUtil.formatDayToStr(time);
        //喂药次数
        int count = (int) medicationRecordList.stream().filter(s -> StringUtils.equals(s.getChildId(), childId))
                .filter(s -> DateUtil.formatDayToStr(s.getEventTime()).equals(time_v1)).count();
        String medicationRecord = "";
        if (count>0){
            medicationRecord = "在托婴中心托育时段共用药" + count + "次";
        }
        return medicationRecord;
    }

}

